# -*- coding: utf-8 -*-

from sqlalchemy import func

from common.chase.model import *
from common.utils import track_logging
from common.utils.db import list_object
from common.utils.db import paginate
from common.utils.decorator import sql_wrapper

_LOGGER = track_logging.getLogger(__name__)


@sql_wrapper
def create_order(params):
    chase_order = ChaseOrder()
    for k, v in params.iteritems():
        setattr(chase_order, k, v)
    chase_order.status = CHASE_ORDER_STATUS.CREATED
    chase_order.save()
    return chase_order


@sql_wrapper
def get_order(order_id):
    return ChaseOrder.query.filter(ChaseOrder.id == order_id).first()


@sql_wrapper
def list_order(query_dct):
    query, total_count = list_object(query_dct, ChaseOrder, disable_paginate=True)
    total_amount = query.with_entities(func.sum(ChaseOrder.amount)).scalar() or 0
    query = paginate(query, query_dct)
    return query.all(), total_count, total_amount


@sql_wrapper
def update_order(order_id, review_type):
    chase_order = ChaseOrder.query.filter(ChaseOrder.id == order_id).first()
    chase_order.status = CHASE_ORDER_STATUS.SUCC if review_type else CHASE_ORDER_STATUS.FAIL
    chase_order.save()
